package com.ynet.middleground.user.service.impl;

import java.util.List;

import javax.validation.Valid;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.ynet.middleground.user.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Throwables;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.user.bean.*;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.dto.DingTalkSearchOrgRelationDTO;
import com.ynet.middleground.user.dto.EmployeeInfoDto;
import com.ynet.middleground.user.dto.OrganizationalStructureDto;
import com.ynet.middleground.user.model.OrganizationManagementModel;
import com.ynet.middleground.user.model.UserRoleRelationModel;
import com.ynet.middleground.user.service.OrganizationManagementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * @program: 2019-10-12_userCenter
 * @description: 组织管理服务实现类
 * @author: DaiGaoLe
 * @create: 2019-10-23 17:43
 **/
@Path("organization-management")
@Produces({MediaType.APPLICATION_JSON + "; " + "charset=UTF-8", MediaType.TEXT_XML + "; " + "charset=UTF-8"})
@Api(value = "港内员工及组织管理服务实现类", tags = {"港内员工及组织管理服务实现类"})
@Service(timeout = 6000, version = "0.0.1")
public class OrganizationManagementServiceImpl implements OrganizationManagementService, GenericService {

    @Autowired
    OrganizationManagementModel organizationManagementModel;

    @Autowired
    private UserRoleRelationModel userRoleRelationModel;

    /* 添加港内员工 begin */

    /**
     * @program: 2019-10-12_userCenter
     * @description: 添加港内员工服务
     * @author: DaiGaoLe
     * @create: 2019-10-23 15:25
     **/
    @POST
    @Path("add")
    @ApiOperation(value = "港内员工数据添加", notes = "港内员工数据添加")
    @Override
    public ServiceResult<Integer> addEmployee(AddEmployeeReq requestObject) {
        ServiceResult<Integer> result = new ServiceResult<>();
        Integer userId = null;
        try {
            userId = organizationManagementModel.addEmployee(requestObject);
        } catch (BusinessException be) {
            result.setError(be.getCode(), be.getMessage());
            return result;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            result.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return result;
        }
        result.setResult(userId);
        return result;
    }
    /* 添加港内员工 end */

    /* 添加机构/部门 begin */
    @POST
    @Path("add-organizational")
    @ApiOperation(value = "港内组织机构/部门添加", notes = "港内组织机构/部门添加")
    @Override
    public ServiceResult<Integer> addOrganizationalStructure(OrganizationalStructureReq requestObject) {
        ServiceResult<Integer> resultService = new ServiceResult<>();
        Integer organizationalId = null;
        try {
            organizationalId = organizationManagementModel.addOrganizationalStructure(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(organizationalId);
        return resultService;

    }
    /* 添加机构/部门 end */

    /* 查询机构/部门 begin */
    @POST
    @Path("info")
    @ApiOperation(value = "港内组织机构/部门查询（不包含该组织的员工数量）",
        notes = "港内组织机构/部门查询(当渠道为综合管理平台，产融核心，易融和山港易付时上传queryChannel字段则内管配置的跨渠道查询失效)")
    @Override
    public ServiceResult<List<OrganizationalStructureDto>>
        queryOrganizationalStructureInfo(QueryOrganizationalStructureReq requestObject) {
        ServiceResult<List<OrganizationalStructureDto>> resultService = new ServiceResult<>();
        List<OrganizationalStructureDto> organizationalStructureDtoList = null;
        try {
            organizationalStructureDtoList =
                organizationManagementModel.queryOrganizationalStructureInfo(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setPagerInfo(requestObject.getPagerInfo());
        resultService.setResult(organizationalStructureDtoList);
        return resultService;
    }

    /* 查询机构/部门 end */
    @POST
    @Path("queryOrganizationalStructureInfoWithCounts")
    @ApiOperation(value = "港内组织机构/部门查询（包含该组织的员工数量）",
        notes = "港内组织机构/部门查询(当渠道为综合管理平台，产融核心，易融和山港易付时上传queryChannel字段则内管配置的跨渠道查询失效)")
    @Override
    public ServiceResult<List<OrganizationalStructureWithCountsDto>>
        queryOrganizationalStructureInfoWithCounts(QueryOrganizationalStructureReq requestObject) {
        ServiceResult<List<OrganizationalStructureWithCountsDto>> resultService = new ServiceResult<>();
        List<OrganizationalStructureWithCountsDto> organizationalStructureDtoList = null;
        try {
            organizationalStructureDtoList =
                organizationManagementModel.queryOrganizationalStructureInfoWithCounts(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setPagerInfo(requestObject.getPagerInfo());
        resultService.setResult(organizationalStructureDtoList);
        return resultService;
    }

    /* 修改机构/ 部门 begin */
    @POST
    @Path("modify-organizational")
    @ApiOperation(value = "港内组织机构/部门修改", notes = "港内组织机构/部门修改")
    @Override
    public ServiceResult<String> modifyOrganizationalStructureReq(ModifyOrganizationalStructureReq requestObject) {
        ServiceResult<String> resultService = new ServiceResult<>();
        String result = null;
        try {
            result = organizationManagementModel.modifyOrganizationalStructureReq(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        return resultService.setResult(result);
    }
    /* 修改机构/ 部门 end */

    /*  删除机构/部门 begin */
    @DELETE
    @Path("organizational")
    @ApiOperation(value = "港内组织机构/部门删除", notes = "港内组织机构/部门删除")
    @Override
    public ServiceResult<String> deleteOrganizationalStructure(DeleteOrganizationalStructureReq requestObject) {
        ServiceResult<String> resultService = new ServiceResult<>();
        String result = null;
        try {
            result = organizationManagementModel.deleteOrganizationalStructure(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(result);
        return resultService;
    }
    /*  删除机构/部门 end */

    /* 查询港内员工信息服务 begin */
    @POST
    @Path("employee")
    @ApiOperation(value = "港内员工数据查询", notes = "港内员工数据查询")
    @Override
    public ServiceResult<List<EmployeeInfoDto>> queryEmployee(QueryEmployeesInfoReq requestObject) {
        ServiceResult<List<EmployeeInfoDto>> resultService = new ServiceResult<>();
        List<EmployeeInfoDto> resultDtos = null;
        try {
            resultDtos = organizationManagementModel.queryEmployee(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(resultDtos);
        resultService.setPagerInfo(requestObject.getPagerInfo());
        return resultService;
    }
    /* 查询港内员工信息服务 end */

    /* 修改港内员工信息 begin */
    @POST
    @Path("modify-employees")
    @ApiOperation(value = "港内员工数据修改", notes = "港内员工数据修改")
    @Override
    public ServiceResult<String> changeEmployeesInfo(ChangeEmployeesInfoReq requestObject) {
        ServiceResult<String> resultService = new ServiceResult<>();
        String result = null;
        try {
            result = organizationManagementModel.changeEmployeesInfo(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(result);
        return resultService;
    }
    /* 修改港内员工信息 end */

    /* 查询港内员工信息服务钉钉专用 begin */
    @POST
    @Path("dingtalk-employee")
    @ApiOperation(value = "港内员工数据查询不分页-钉钉专用", notes = "港内员工数据查询不分页-钉钉专用")
    @Override
    public ServiceResult<List<DingTalkSearchOrgRelationDTO>>
        queryDingTalkEmployee(QueryDingTalkEmployeesInfoReq requestObject) {
        ServiceResult<List<DingTalkSearchOrgRelationDTO>> resultService = new ServiceResult<>();
        List<DingTalkSearchOrgRelationDTO> resultDtos = null;
        try {
            resultDtos = organizationManagementModel.queryDingTalkEmployee(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(resultDtos);
        return resultService;
    }

    /**
     * 港内员工数据查询(移动审批专用)
     *
     * @param requestObject
     * @return
     */
    @POST
    @Path("queryEmployeesForMobile")
    @ApiOperation(value = "港内员工数据查询(移动审批专用)", notes = "港内员工数据查询(移动审批专用)")
    @Override
    public ServiceResult<List<DingTalkSearchEmployeesDTO>>
        queryEmployeesForMobile(@Valid DingTalkSearchEmployeesInfoReq requestObject) {
        ServiceResult<List<DingTalkSearchEmployeesDTO>> resultService = new ServiceResult<>();
        List<DingTalkSearchEmployeesDTO> list = null;
        try {
            list = userRoleRelationModel.queryEmployeesForMobile(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(list);
        return resultService;
    }

    /**
     * 获取港内组织上下级ID
     *
     * @param req
     * @return
     */
    @POST
    @Path("parentAndChildOrganizationIds")
    @ApiOperation(value = "获取港内组织上下级ID（移动审批专用）", notes = "获取港内组织上下级ID（移动审批专用）")
    @Override
    public ServiceResult<List<String>> parentAndChildOrganizationIds(@Valid GetParentAndChildReq req) {
        ServiceResult<List<String>> resultService = new ServiceResult<>();
        List<String> list = null;
        try {
            list = userRoleRelationModel.parentAndChildOrganizations(req.getOperateChannels(), req.getId());
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(list);
        return resultService;
    }
    //
    // @POST
    // @Path("organizationalname-by-teloraccount")
    // @ApiOperation(value = "根据手机号或账号获取港内员工所属组织机构id及名称", notes = "根据手机号或账号获取港内员工所属组织机构id及名称")
    // @Override
    // public ServiceResult<List<OrganizationalListInfoDto>> pursuantTelephoneGetUserName(TelephoneGetUserNameReq
    // requestObj) {
    // ServiceResult<List<OrganizationalListInfoDto>> serviceResult = new ServiceResult<>();
    // List<OrganizationalListInfoDto> result = null;
    // try {
    // result = organizationManagementModel.pursuantTelephoneGetUserName(requestObj);
    // } catch (BusinessException be) {
    // serviceResult.setError(be.getCode(), be.getMessage());
    // return serviceResult;
    // } catch (Exception e) {
    // // 获取当前方法名
    // IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
    // Throwables.getStackTraceAsString(e));
    // serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
    // return serviceResult;
    // }
    // serviceResult.setResult(result);
    // return serviceResult;
    // }
}
